﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;

/// <summary>
/// 运行时动态添加参考图像
/// </summary>
public class DynamicImageTracking : MonoBehaviour
{
    [SerializeField]
    private GameObject mPrefabOnTrack;

    private Vector3 scaleFactor = new Vector3(0.2f, 0.2f, 0.1f);

    private XRReferenceImageLibrary mRuntimeImageLibrary;
    private ARTrackedImageManager mTrackImageManager;

    [SerializeField]
    private Texture2D mAddedImage;

    // Start is called before the first frame update
    void Start()
    {
        //mTrackImageManager = gameObject.AddComponent<ARTrackedImageManager>();
        //mTrackImageManager.referenceLibrary = mTrackImageManager.CreateRuntimeLibrary(mRuntimeImageLibrary); ;
        //mTrackImageManager.maxNumberOfMovingImages = 2;
        //mTrackImageManager.trackedImagePrefab = mPrefabOnTrack;
        //mTrackImageManager.enabled = true;
        //mTrackImageManager.trackedImagesChanged += OnTrackedImagesChanged;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnDisable()
    {
        mTrackImageManager.trackedImagesChanged -= OnTrackedImagesChanged;
    }

    //public IEnumerator DynamicAddImage()
    //{
    //    return AddImageJob(mAddedImage);
    //}

    //private IEnumerator AddImageJob(Texture2D texture2D)
    //{
        //yield return null;

        //try
        //{
        //    MutableRuntimeReferenceImageLibrary mutableRuntimeReferenceImageLibrary = mTrackImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;
        //    var jobHandle = mutableRuntimeReferenceImageLibrary.ScheduleAddImageJob(texture2D, "Spider", scaleFactor.x);

        //    while (!jobHandle.IsCompleted)
        //    {
        //        new WaitForSeconds(0.5f);
        //    }

        //    ToastUtil.showToast("添加图像成功");
        //}
        //catch(System.Exception e)
        //{
        //    ToastUtil.showToast("DynamicImageTracking AddImageJob Exception =" + e.Message);
        //}
    //}

    void OnTrackedImagesChanged(ARTrackedImagesChangedEventArgs eventArgs)
    {
        foreach (ARTrackedImage trackedImage in eventArgs.added)
        {
            trackedImage.transform.Rotate(Vector3.up, 180);
        }

        foreach(ARTrackedImage trackedImage in eventArgs.updated)
        {
            trackedImage.transform.Rotate(Vector3.up, 180);
        }
    }

}
